<?php

namespace App\Console\Commands;

use App\Models\Base\KeepStatistic;
use App\Models\Base\ServerList;
use App\Service\AccountService;
use App\Service\ChannelService;
use App\Service\PlayerService;
use App\Service\ServerService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class FetchUserRemain extends CommandBase
{
    /**
     * 统计用户留存.
     *
     * @var string
     */
    protected $signature = 'fetch:userRemain {dateTime?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户留存统计';

    /**
     * 留存天数.
     *
     * @var array
     */
    protected $retainedDays;

    protected $model;

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
        $this->retainedDays = [
            1 => 'two_rate',
            2 => 'three_rate',
            3 => 'four_rate',
            4 => 'five_rate',
            5 => 'six_rate',
            6 => 'seven_rate',
            14 => 'fifteen_rate',
            29 => 'thirty_rate',
        ];
        $this->model = new KeepStatistic();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $dateTime = $this->argument('dateTime');
        if ($dateTime) {
            $this->today = $dateTime;
            $this->todayTimestamp = strtotime($dateTime);
            $this->yesterdayTimestamp = $this->todayTimestamp - 86400;
            $this->yesterday = date('Y-m-d', $this->yesterdayTimestamp);
        }
        try {
            //全服留存
            $this->platformStat();
            //区服留存
            $this->serverStat();
            //渠道统计
            $this->channelStat();
        } catch (\Exception $e) {
            Log::error('统计留存错误'.$e->getMessage().'line:'.$e->getLine());
            dd($e);
        }
    }

    /**
     * 区服留存统计
     */
    protected function serverStat()
    {
        $server_ids = ServerService::serverIds();
        foreach ($server_ids as $server_id) {
            $this->model = new KeepStatistic();
            setDB($server_id);
            $this->model->type = self::STAT_TYPE_SERVER;
            $this->model->date_time = $this->yesterday;
            $this->model->server_id = $server_id;
            //新增角色
            $new_roles = PlayerService::getSignPlayer($this->yesterdayTimestamp, $this->todayTimestamp)->count();
            $this->model->new_users = $this->model->new_roles = $new_roles;
            $this->model->save();

            foreach ($this->retainedDays as $day => $val) {
                //往日数据
                $bygone_day =  date('Y-m-d',$this->todayTimestamp - self::DAY_TIMESTAMP * $day);
                $bygone_yesterday =  date('Y-m-d',$this->todayTimestamp - self::DAY_TIMESTAMP * ($day+1));
                $keep = KeepStatistic::where('date_time', $bygone_yesterday)->where('server_id', $server_id)->first();
                if (!$keep) {
                    continue;
                }
                //当日登录角色
                $remain = PlayerService::getTodayPlayerNum(strtotime($bygone_yesterday), strtotime($bygone_day));
                if ($remain->isEmpty()) {
                    continue;
                }
                $role_ids = $remain->pluck('playerid')->all();
                $keep_number = PlayerService::playerLoginCount($this->yesterdayTimestamp, $this->todayTimestamp, $role_ids)->count();
                $keep->$val = $keep->new_users ? $keep_number / $keep->new_users : 0;
                $keep->save();
            }
        }
    }

    protected function channelServerStat()
    {
        $serverIds = ServerList::all()->pluck('server_id');
        $channelIds = ChannelService::getChannelIds();
        if($serverIds->isEmpty() || empty($channelIds)){
            return false;
        }
        foreach ($serverIds as $serverId){
            setDB($serverId);
        }
    }


    /**
     * 渠道用户留存统计
     */
    protected function channelStat()
    {
        $channelIds = ChannelService::getChannelIds();
        if (empty($channelIds)) {
            return false;
        }
        foreach ($channelIds as $channel_value) {
            $channel_id = $channel_value['channel_no'];
            $platform_id = $channel_value['pid'];
            $this->model = new KeepStatistic();
            $this->model->type = self::STAT_TYPE_CHANNEL;
            $this->model->date_time = $this->yesterday;
            $this->model->channel_id = $channel_id;
            $this->model->platform_id = $platform_id;
            //注册数量
            $this->model->new_users = ChannelService::registerUsers($this->yesterdayTimestamp, $this->todayTimestamp, $channel_id)->count();
            //创角数量
            $this->model->new_roles = $this->newRolesNumber($channel_id);
            $this->model->save();
            foreach ($this->retainedDays as $day => $val) {
                //往日数据
                $bygone_day =  date('Y-m-d',$this->todayTimestamp - self::DAY_TIMESTAMP * $day);
                $bygone_yesterday =  date('Y-m-d',$this->todayTimestamp - self::DAY_TIMESTAMP * ($day+1));
                $keep = KeepStatistic::where('date_time', $bygone_yesterday)->where('channel_id', $channel_id)->first();
                if (!$keep) {
                    continue;
                }
                $this->updateKeep(strtotime($bygone_yesterday), strtotime($bygone_day), $keep, $val, $channel_id);
            }
        }
    }

    /**
     * 全平台留存统计
     */
    protected function platformStat()
    {
        $this->model->date_time = $this->yesterday;
        $this->model->type = self::STAT_TYPE_PLATFORM;
        //新增用户
        $new_users = AccountService::signNumber($this->yesterdayTimestamp, $this->todayTimestamp);
        $this->model->new_users = $new_users->count();
        //新增角色
        $this->model->new_roles = $this->newRolesNumber();
        $this->model->save();
        foreach ($this->retainedDays as $day => $val) {
            //往日数据
            $bygone_day =  date('Y-m-d',$this->todayTimestamp - self::DAY_TIMESTAMP * $day);
            $bygone_yesterday =  date('Y-m-d',$this->todayTimestamp - self::DAY_TIMESTAMP * ($day+1));
            $keep = KeepStatistic::where('date_time', $bygone_yesterday)->where('type', self::STAT_TYPE_PLATFORM)->first();
            if (!$keep) {
                continue;
            }
            $this->updateKeep(strtotime($bygone_yesterday), strtotime($bygone_day), $keep, $val);
        }
    }

    /**
     * 更新往日留存数据.
     */
    protected function updateKeep($start_at, $end_at, KeepStatistic $keep, $val, $channel_id = null)
    {
        //当日登录用户
        $accounts = AccountService::signNumber($start_at, $end_at, $channel_id);
        if ($accounts->isEmpty()) {
            return false;
        }
        $userIds = $accounts->pluck('ac_id')->all();
        $now_login_count = AccountService::loginByUserIds($userIds, $this->yesterdayTimestamp, $this->todayTimestamp)
            ->count();
        $keep->$val = $keep->new_users ? $now_login_count / $keep->new_users : 0;
        $keep->save();
    }

    /**
     * 昨日新增角色数量.
     *
     * @return int
     */
    protected function newRolesNumber($channel_id = null)
    {
        $role_numbers = 0;
        $server_ids = ServerService::serverIds();
        foreach ($server_ids as $server_id) {
            setDB($server_id);
            $number = PlayerService::getSignPlayer($this->yesterdayTimestamp, $this->todayTimestamp, $channel_id)->count();
            $role_numbers += $number;
        }

        return $role_numbers;
    }
}
